package com.syq.service.impl;

import com.github.pagehelper.PageInfo;
import com.syq.mapper.ProfileDao;
import com.syq.pojo.Profile;
import com.syq.service.ProfileService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @ClassName: ProfileServiceImpl
 * @Description: TODO
 * @Create by: syq
 * @Date: 4/7/2022 下午5:37
 */


public class ProfileServiceImpl implements ProfileService {
    @Override
    public Profile findById(int id) {
        InputStream is = null;
        try {
            is = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        ProfileDao profileMapper = sqlSession.getMapper(ProfileDao.class);
        return profileMapper.selectById(id);
    }

    @Override
    public void update(Profile profile) {
        InputStream is = null;
        try {
            is = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        ProfileDao profileMapper = sqlSession.getMapper(ProfileDao.class);
        profileMapper.update(profile);
        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public void add(Profile profile) {
        InputStream is = null;
        try {
            is = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        ProfileDao profileMapper = sqlSession.getMapper(ProfileDao.class);
        profileMapper.add(profile);
        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public List<Profile> findAll() {
        InputStream is = null;
        try {
            is = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        ProfileDao profileMapper = sqlSession.getMapper(ProfileDao.class);
        return profileMapper.selectAll();
    }


}
